package com.aisino.api.util;

import cn.hutool.core.io.FileUtil;

import java.util.*;
import java.util.regex.*;
import java.util.AbstractMap;

public class SpecNormalizer {

    private static final Map<String, String> UNIT_MAP = new HashMap<>() {{
        put("小袋", "袋");
    }};

    private static final Pattern COUNT_PATTERN = Pattern.compile(
            "(\\d+(?:\\.\\d+)?)\\s*(小袋|粒|片|袋|支|丸|瓶|板|包|贴|只)",  // 👈 加入 "只"
            Pattern.CASE_INSENSITIVE
    );

    // 常见计数类包装单位，用于兜底逻辑
    private static final Set<String> COUNT_UNITS = new HashSet<>(Arrays.asList(
            "支", "盒", "瓶", "袋", "包", "板", "贴", "粒", "片", "小袋", "只"
    ));

    public static List<Map.Entry<Double, String>> normSpec(String spec) {
        List<Map.Entry<Double, String>> result = new ArrayList<>();

        if (spec == null || spec.trim().isEmpty()) {
            return result;
        }

        String text = spec.toLowerCase().replace(" ", "");

        // 1. 先用标准正则提取数字 + 计数单位
        Matcher matcher = COUNT_PATTERN.matcher(text);
        while (matcher.find()) {
            try {
                double num = Double.parseDouble(matcher.group(1));
                String unit = matcher.group(2);
                String normalizedUnit = UNIT_MAP.getOrDefault(unit, unit);
                result.add(new AbstractMap.SimpleEntry<>(num, normalizedUnit));
            } catch (Exception ignored) {}
        }

        // 2. 如果没有提取到任何计数单位，但字符串中有 /支、/盒 等 → 默认 1 支/盒
        if (result.isEmpty()) {
            for (String unit : COUNT_UNITS) {
                if (text.contains("/" + unit)) {
                    result.add(new AbstractMap.SimpleEntry<>(1.0, unit));
                    break; // 只加一个默认
                }
            }
        }

        // 排序
        result.sort(Comparator.comparing(Map.Entry::getKey));
        return result;
    }

    // 测试
    public static void main(String[] args) {
        List<String> testCases =FileUtil.readUtf8Lines("c:/1.txt");

        for (String tc : testCases) {
            List<Map.Entry<Double, String>> res = normSpec(tc);
            if (res.isEmpty()) {
                System.out.println("输入: \"" + tc + "\"");
                System.out.println("  → 未解析到有效的【计数类】规格");
            } else {
                for (Map.Entry<Double, String> entry : res) {
                    //System.out.printf("  → 数值: %.1f, 单位: \"%s\"%n", entry.getKey(), entry.getValue());
                }
            }
            System.out.println();
        }
    }
}
